﻿using Castle.Core.Logging;

using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;

using PLCS.Application.Contracts.EquipmentApp.Dtos;
using PLCS.Domain.Equipments;
using PLCS.Domain.Stations;

using Volo.Abp.AspNetCore.SignalR;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.EquipmentApp.Hubs;

public class FrameHub : AbpHub
{
    private readonly IEquipmentRepository _equipmentRepository;
    private readonly IStationRepository _stationRepository;
    private readonly ILogger<FrameHub> _logger;

    public FrameHub(IEquipmentRepository equipmentRepository, IStationRepository stationRepository, ILogger<FrameHub> logger)
    {
        _equipmentRepository = equipmentRepository;
        _stationRepository = stationRepository;
        _logger = logger;
    }

    public override Task OnConnectedAsync()
    {
        return base.OnConnectedAsync();
    }

    public async Task InitalStatus(string name)
    {
        try
        {
            Equipment equipment = await _equipmentRepository.FindAsync(x => x.EquName == name);
            if (equipment != null)
            {
                await Clients.Caller.SendAsync("ChangeEquipmentStatus", name, equipment.Status);
                switch (equipment.EquType)
                {
                    case EquipmentType.RGV:
                        await Clients.Caller.SendAsync("ChangeEquipmentLocation", name, equipment.CurrentStation);
                        break;

                    case EquipmentType.Stacker:
                        //await Clients.All.SendAsync("ChangeCranePosition", name, "RG1", equipment.CurrentStation);
                        break;

                    case EquipmentType.ConveyorLine:
                        break;

                    case EquipmentType.AGV:
                        break;

                    case EquipmentType.RotaryTable:
                        break;

                    default:
                        break;
                }
            }
            Station station = await _stationRepository.FindAsync(x => x.StaName == name);
            if (station != null)
            {
                await Clients.Caller.SendAsync("ChangeStationStatus", name, station.HaveStatus);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError($"初始化状态失败，异常信息：{ex.Message}");
        }
    }
}